<template>
  <el-select
    v-model="labels"
    filterable
    :filter-method="PinyinMatchFun"
    :multiple="false"
    :placeholder="`请选择${order}`"
    ref="template"
    :disabled="disabledSelect"
    clearable
    @visible-change="(v) => visibleChange(v, 'template')"
    @change="changeEvent"
    :popper-append-to-body="false"
    @clear="handleClear"
  >
    <el-option
      v-for="(item, index) in labelslist"
      :key="index"
      :label="item[label]"
      :value="item[val]"
      style="width: 220px"
    >
      <!-- {{ item[label] }} -->
      <!-- {{ item[label] }} -->
      <el-tooltip
        v-if="item[label].length > 15"
        class="item"
        effect="dark"
        :content="item[label]"
        placement="top-start"
      >
        <span class="labelStyle">{{ item[label] }}</span>
      </el-tooltip>
      <span v-else class="labelStyle">{{ item[label] }}</span>
      <span
        v-if="delFlag"
        style="float: right; z-index: 20"
        class="span-style"
        @click="delItem(item[val])"
      >
        <i class="el-icon-close"></i>
      </span>
      <div class="flag" @click="showShipTemplate(item.code, true)"></div>
    </el-option>
  </el-select>
</template>
<script>
import PinyinMatch from 'pinyin-match'
import { checkInsertOwnerName, checkInsertTestUnitName } from '@/api/dict.js'
export default {
  name: 'selectAdd',
  props: {
    // 最开始的下拉列表数据
    labelslist: {
      type: Array,
      default: [],
    },
    labelslistCopy: {
      type: Array,
      default: () => [],
    },
    // 新增选项的接口
    api: {
      type: Function,
    },
    delApi: {
      type: Function,
    },
    // 新增选项的字段
    query: {
      type: String,
      default: 'stationName',
    },
    // 下拉框label绑定显示的字段名
    label: {
      type: String,
      default: 'stationName',
    },
    // 下拉框label绑定数据的字段名
    val: {
      type: String,
      default: 'stationId',
    },
    // 下拉框的名字
    order: {
      type: String,
      default: '厂站名称:',
    },
    // 外部绑定的下拉框的数据
    formVla: {
      type: String,
      default: '',
    },
    // 所属调管调度机构的字段名
    regulation: {
      type: String,
      default: '',
    },
    // 所属调管调度机构绑定的数据
    regulationOrgId: {
      type: String,
      default: '',
    },
    // 厂站名称的数据
    stationTypes: {
      type: String,
      default: '',
    },
    // 新能源场站
    stationCategory: {
      type: String,
      default: '',
    },
    disabledSelect: {
      type: Boolean,
      default: false,
    },
    PinyinMatchFun: {
      type: Function,
    },
    delFlag: {
      //是否显示x  删除
      type: Boolean,
      default: true,
    },
    // 发电集团绑定的数据
    companyId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      // 数据源
      //labelslist: [],
      // 复制一份数据
      //labelslistCopy: [],
      labels: '',
      params: {},
    }
  },
  created() {
    this.labels = this.formVla
    //this.labelslistCopy = JSON.parse(JSON.stringify(labelslist))
  },
  methods: {
    changeEvent(e) {
      this.$emit('changeEvent', e)
    },
    getData(api) {
      // let loadingInstance = Loading.service({ fullscreen: true });
      // console.log(loadingInstance,'_____________23141234')
      this.params[this.label] = this.labels
      if (this.regulation) this.params[this.regulation] = this.regulationOrgId
      if (this.stationTypes) this.params['stationType'] = this.stationTypes
      if (this.stationCategory)
        this.params['stationCategory'] = this.stationCategory
      if (this.companyId) this.params['ownersId'] = this.companyId
      //console.log(this.params, '_____________23141234')
      return new Promise(() => {
        api(this.params)
          .then((res) => {
            if (res.code === '000000') {
              this.$message.success('新增成功!')
              this.$emit('getQueryStationList', true)
            }
            // if (res.code === '400002') {
            //   this.$confirm(res.mesg, '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning',
            //   })
            // }
          })
          .catch(() => {
            this.$message.error('数据加载失败!')
          })
      })
    },
    // 添加商品标签
    showShipTemplate() {
      this.$prompt(`请输入新的${this.order}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action == 'confirm') {
            //点击确认请求接口
            if (this.order == '产权单位') {
              let res = await checkInsertOwnerName({
                ownersName: instance.inputValue,
              })
              // 根据接口返回值判断是否有重复，重新填写或者通过
              if (res.code === '400002') {
                // 通过监测关闭
                this.$message.error(res.mesg)
              } else {
                done()
              }
            }

            if (this.order == '试验单位') {
              let res = await checkInsertTestUnitName({
                testingUnitName: instance.inputValue,
              })
              // 根据接口返回值判断是否有重复，重新填写或者通过
              if (res.code === '400002') {
                // 通过监测关闭
                this.$message.error(res.mesg)
              } else {
                done()
              }
            }

            // console.log(res);
          } else {
            //点击取消关闭
            done()
          }
        },

        //校验方法
        inputValidator: (val) => {
          if (val.length > 40) {
            return '最多可输入40个字符'
          }

          // this.labelslist.forEach((item) => {
          //   if (item.unitsName === val) {
          //     console.log(item.unitsName === val, '98999')
          //     return '请重新输入'
          //   }
          // })
        },
        //inputErrorMessage: '最多可输入40个字符',
      }).then(({ value }) => {
        this.labels = value
        this.getData(this.api)
      })
    },
    visibleChange(visible, refName) {
      this.$nextTick(() => {
        if (visible) {
          const ref = this.$refs[refName]
          let popper = ref.$refs.popper
          if (popper.$el) popper = popper.$el
          if (
            !Array.from(popper.children).some(
              (v) => v.className === 'el-template-menu__list'
            )
          ) {
            const el = document.createElement('ul')
            el.className = 'el-template-menu__list'
            el.style =
              'border-bottom:2px solid rgb(219 225 241); padding:0; color:rgb(64 158 255);font-size: 13px;margin: 0px;text-align: center; '
            el.innerHTML = `<li class="el-cascader-node text-center" style="height:36px;line-height: 36px;">
            <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i>添加${this.order}</span>
            </li>`
            // console.log(
            //   document.querySelector(".el-scrollbar"),
            //   "sssssssssssssss"
            // );
            // console.log(popper.childNode,'sssssssssssssss')
            // console.log(popper.children[0], "231111111111");
            // console.log(popper, "popper");
            //   popper.appendChild(el,);
            popper.insertBefore(el, popper.children[0])
            el.onclick = () => {
              this.showShipTemplate(null, false)
            }
          }
        }
      })
    },
    delItem(param) {
      console.log(param)
      let val = {}
      val[this.val] = param
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        // 发送请求
        const res = await this.delApi(val)
        if (res.code == '000000') {
          console.log(res) // 确认删除
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.labels = ''
          this.$emit('getQueryStationList', true)
        }
      })
    },

    handleClear() {
      this.value = '' // 清空选中的值
      this.$emit('handleClear', this.labels)
    },
    // 过滤方法, 接收一个输入框内容作为参数, 当输入框内容改变后会执行
    // PinyinMatchFun(val) {
    //   if (val) {
    //     // 定义一个空数组用来存储过滤后的数据
    //     var result = []
    //     // 开始循环过滤内容
    //     this.labelslistCopy.forEach((i) => {
    //       // 调用 PinyinMatch.match 方法进行拼音与汉字匹配
    //       var m = PinyinMatch.match(i.label, val)
    //       if (m) {
    //         // 匹配成功则push到result数组中
    //         result.push(i)
    //       }
    //     })
    //     // 将过滤后的数组重新赋给下拉列表数据
    //     this.labelslist = result
    //     this.value = val
    //   } else {
    //     // 如果输入框为空, 则将下拉列表数据还原
    //     this.labelslist = this.labelslistCopy
    //   }
    // },
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-cascader-node {
  text-align: center;
}
.labelStyle {
  float: left;
  display: inline-block;
  max-width: 145px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
</style>
